#include "Sock.hpp"
#include "Protocol.hpp"
#include <pthread.h>
static void Usage(string proc)
{
    cout << "Usage:" << proc << "port" << endl;
    exit(1);
}

void *HandlerRequest(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;
    pthread_detach(pthread_self());
    // 业务逻辑
    // 1.读取请求
    request_t req;
    ssize_t s = read(sock, &req, sizeof(req));
    // 2.分析请求
    // 3.计算结果
    // 4.构建响应
    if (s == sizeof(req))
    {
        response_t resp = {0, 0};
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
            if (req.y == 0)
            {
                resp.code = -1;
            }
            else
            {
                resp.result = req.x / req.y;
            }
            break;
        case '%':
            if (req.y == 0)
            {
                resp.code = -2;
            }
            else
            {
                resp.result = req.x / req.y;
            }
            break;

        default:
            resp.code = -3;
            break;
        }
        cout << req.x << req.op << req.y << endl;
        write(sock, &resp, sizeof(resp));
    }

    // 5.关闭链接
    close(sock);
}
int main(int argc, char *argv[])
{
    if (argc != 2)
        Usage(argv[0]);
    uint16_t port = atoi(argv[1]);

    int listen_sock = Sock::Socket();
    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);
    for (;;)
    {
        int sock = Sock::Accept(listen_sock);
        if (sock >= 0)
        {
            cout << "get a new client..." << endl;
            int *pram = new int(sock);
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerRequest, pram);
        }  
    }
    return 0;
}